let Rule = require('./rule.js')
class Check{
	constructor(rules,i18n){
		this._check = true
		this._errors = {}
		this._error = null
		this._rules = rules
		this._i18n = i18n
		this._running = true
	}
	run(values,rules,messages,attributes){
		for(var key in rules){
			if(this._running){
				this.#check(key,values,rules[key],messages,attributes?attributes[key]:null)
			}
		}
		return this
	}
	#check(key,values,rulestr,messages,attribute){	
		var rules = rulestr.split("|")
		for(var i in rules){
			let ruleName = rules[i].split(":")[0]
			let params = [];
			if(typeof rules[i].split(":")[1] !== 'undefined'){
				params = rules[i].split(":")[1].split(",")
			}
			if(typeof this._rules[ruleName] === 'undefined'){
				console.error(ruleName+"校验规则不存在！")
				this._check = false
				this._running = false
				break;
			}
			let rule = new this._rules[ruleName](key,values,messages?messages[ruleName]:null,attribute,params,this._i18n)
			let check = rule.$check
			if(ruleName === 'nullable'){
				if(check){
					break;
				}
			}else if(!check){
				this._check = false
				if(typeof this._errors[key] != undefined){
					this._errors[key] = [];
				}
				this._error = this._error?this._error:rule.$message;
				this._errors[key].push(rule.$message);
			}
		}
	}
	passes(){
		return this._check
	}
	errors(key){
		return key?this._errors:this._errors[key]
	}
	error(){
		return this._error
	}
	hasError(key){
		return typeof this._errors[key] !== 'undefined'
	}
}
module.exports = Check